package cn.donting.jem.runtime.mesh;

import com.jme3.math.FastMath;
import com.jme3.scene.Mesh;

import java.util.ArrayList;


public class Cone extends Mesh {
    private float radius;
    private float height;
    private float radialSamples;

    public Cone() {
        this(0.5f, 1f,20);
    }

    public Cone(float radius, float height,int radialSamples) {
       updateGeometry(radius,height,radialSamples);
    }


    public void updateGeometry(float radius, float height,int radialSamples){
        this.height = height;
        this.radius = radius;
        this.radialSamples = radialSamples;

        ArrayList<float[]> vertices = generateConeVertices(radius, height, radialSamples);
        ArrayList<int[]> triangles = generateConeTriangles(radialSamples);

        updateBound();
        setStatic();
    }



    private static ArrayList<float[]> generateConeVertices(float radius, float height, int numSegments) {
        ArrayList<float[]> vertices = new ArrayList<>();

        // 底部圆的顶点
        for (int i = 0; i < numSegments; i++) {
            float theta = 2.0f * FastMath.PI * i / numSegments;
            float x = radius * FastMath.cos(theta);
            float y = radius * FastMath.sin(theta)-height/2;
            float z = 0.0f;
            vertices.add(new float[]{x, y, z});
        }

        // 顶部点
        vertices.add(new float[]{0.0f, 0.0f, height/2});

        return vertices;
    }

    private static ArrayList<int[]> generateConeTriangles(int numSegments) {
        ArrayList<int[]> triangles = new ArrayList<>();

        // 底部圆上的三角形
        for (int i = 0; i < numSegments; i++) {
            int i1 = i;
            int i2 = (i + 1) % numSegments;
            int topVertexIndex = numSegments;

            triangles.add(new int[]{i1, i2, topVertexIndex});
        }

        return triangles;
    }
}
